export function useWebEnv() {
  let env = "web"
  // #ifdef WEB
  const ua = navigator.userAgent.toLowerCase()
  if (ua.match(/MicroMessenger/i)) env = "wxWeb"
  if (ua.match(/MicroMessenger/i) && ua.match(/miniprogram/i)) env = "wxMp"
  // #endif
  return env
}

// 获取业务环境
export function useWebEvn() {
  const ua = navigator.userAgent.toLowerCase()
  const href = window.location.href.toLowerCase()
  const evns = {
    mp: "mp",
    ali: "ali",
    boc: "boc",
    pab: "pab",
    cib: "cib",
    icbc: "icbc|icbctime",
    ysf: "ysf|ysftime",
    efz: "efz|efztime",
    abc: "abc|abctime",
    yzf: "yzf",
    gat: "gat",
    sft: "sft|sfttime",
    cmbc: "cmbc|cmbccard",
    ulejf: "ulejf",
    test: "test",
    webview: "webview",
    ibl: "ibl",
    web: "web|h5"
  }
  let evn = "web"
  if (ua.match(/MicroMessenger/i)) evn = "wxWeb"
  Object.entries(evns).forEach(([name, rule]) => {
    let str = new RegExp(`evn=(${rule})(?=&|$)`)
    if (str.test(href)) evn = name
  })
  evn = window.sessionStorage.getItem("webEvn") || evn
  return evn
}

/**
 * 加载脚本的方法，返回一个Promise对象。
 * @param {string} url - 要加载的脚本的URL。
 * @returns {Promise} - 表示脚本加载状态的Promise对象。
 */
export function loadScript(url, force = false) {
  return new Promise((resolve, reject) => {
    // 检查是否已经加载过相同的脚本
    if (!force) {
      const scripts = document.getElementsByTagName("script")
      for (let i = 0; i < scripts.length; i++) {
        if (scripts[i].src === url && scripts[i].loaded) {
          resolve() // 已加载过，直接解析Promise
          return
        }
      }
    }

    // 创建新的脚本元素
    const script = document.createElement("script")
    script.src = url

    script.onload = () => {
      script.loaded = true
      resolve()
    }

    script.onerror = () => {
      reject("加载脚本失败: " + url)
    }

    document.head.appendChild(script)
  })
}

/**
 * 延时指定的时间后执行回调函数
 * @param {number} delay - 延时时间（毫秒）
 * @returns {Promise} - 返回一个Promise对象
 */
export function delay(delay) {
  return new Promise((resolve) => {
    setTimeout(resolve, delay)
  })
}
